package com.goldsprite.horipush;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.goldsprite.gameframeworks.assets.GlobalAssets;
import com.goldsprite.gameframeworks.input.GameInputSystem;
import com.goldsprite.gameframeworks.screens.GScreen;
import com.goldsprite.gameframeworks.screens.ScreenManager;
import com.goldsprite.gameframeworks.utils.FontUtils;
import com.goldsprite.gameframeworks.utils.math.Vector2;
import com.goldsprite.horipush.screens.StartScreen;

public class GdxLauncher extends ApplicationAdapter {
	public static final float WORLD_WIDTH = 960;
	public static final float WORLD_HEIGHT = 540;
	public static boolean showFps = true;

	private SpriteBatch batch;
	private BitmapFont font;
	OrthographicCamera cam;

	@Override
	public void create() {
		//实例化全局资源
		new GlobalAssets();

		//初始化输入系统
		ScreenManager.getInstance().getImp().addProcessor(GameInputSystem.getInstance());

		//创建统一视口
		FitViewport viewport = new FitViewport(WORLD_WIDTH, WORLD_HEIGHT);
		viewport.apply(true);

		//初始化屏幕
		ScreenManager.getInstance().
			setViewport(viewport).
			addScreen(new StartScreen()).
			setLaunchScreen(StartScreen.class);

		batch = new SpriteBatch();
		font = FontUtils.generate(35);
		font.getData().setScale(0.45f);

		cam = (OrthographicCamera) ScreenManager.getInstance().getViewport().getCamera();
	}

	@Override
	public void render() {
		ScreenManager.getInstance().render();
		if (showFps) drawFps();
	}

	private void drawFps() {
		batch.setProjectionMatrix(cam.combined);
		batch.begin();
		float margin = 10;

		try (Vector2 mouseWorldPos = Vector2.obtain(Gdx.input.getX(), Gdx.input.getY())) {
			GScreen curScreen = (GScreen)ScreenManager.getInstance().getCurScreen();
			curScreen.screenToWorldCoord(mouseWorldPos);

			String msg = "FPS: " + Gdx.graphics.getFramesPerSecond()
				//+ "\nViewSize: " + curScreen.getViewSize()
				//+ "\nMouseWorldPos: " + mouseWorldPos
				+ "\nGameVersion: " //+ BuildConfig.DEV_VERSION
				//+ "\nJDKVersion: " + BuildConfig.JDK_VERSION
				;
			int lineCount = (int)msg.chars().filter(c -> c == '\n').count() + 1;
			font.draw(batch, msg, margin, margin + lineCount * 20);
		}

		batch.end();
	}

	@Override
	public void resize(int width, int height) {
		ScreenManager.getInstance().resize(width, height);
	}

	@Override
	public void dispose() {
		ScreenManager.getInstance().dispose();
	}

}
